<?php
define('SMARTY_DIR',str_replace("\\","/",getcwd()).'/Smarty/libs/');
require_once(SMARTY_DIR . 'Smarty.class.php');
require_once('settings.php');
require_once('lib/db.php');

class MainRun {
	
	private $debug = true;
	private $smartyDebug = false;
	private $smarty;
	private $siteDetails;
	private $subAction;
	// language file 
	private $lang;
	
	public function run() {
		
		// load settings
		$settings = new settings();
		$language = $settings->getLanguage();
		$langPath = $settings->getLanguagePath();
		
		//load language file
		include $langPath.$language.'.php';
		$this->lang = $lang;
		// self::debug(__LINE__.' lang', $this->lang, 1);	

		$this->siteDetails = $settings->getSiteDetails();

		$subAction = null;
		if (isset($_POST['action'])) {
			$action = $_POST['action'];
		} elseif (isset($_GET['action'])) {
			$action = $_GET['action'];
			if (isset($_GET['subAction'])) {
				$this->subAction = $_GET['subAction'];
			}
		} 
		else {
			$action = 1;
			
		}
		
		// print "$action 	/	$subAction ";
		
		$this->smarty = new Smarty();
		$this->smarty->debugging = $this->smartyDebug;
		// check if user logon
		session_start();
		if (isset($_SESSION['user']['id'])) {
			$this->smarty->assign('userIsLoggedIn', '1');
		}

		$this->buildMenu();
		$this->setCommonTemplateValues();
		switch ($action) {
			case 'band':
				require_once 'band.php';
				$band = new admin($this->lang, $this->siteDetails, $this->debug);
				$template = $band->run($this->smarty);
				break;
			case 'songs':
				$this->displaySongs();
				$this->smarty->assign('menuActive', 2);
				$this->smarty->assign('actionNews', 0);
				$template = 'index.tpl';
				break;
			case 'news':
				$this->smarty->assign('menuActive', 3);
				$template = 'index.tpl';
				break;
			case 'gallery':
				$this->smarty->assign('menuActive', 4);
				$template = 'index.tpl';
				break;	
			case 'about':
				$this->prepareNews();
				$this->displayAbout();
				$this->smarty->assign('menuActive', 5);
				$template = 'index.tpl';
				break;
			case 'emailAdd':
				$this->addEmail;
			case 'contacts':
				$this->prepareNews();
				$this->displayContacts();
				$this->smarty->assign('menuActive', 6);
				$template = 'index.tpl';
				break;
			default :
				$this->prepareNews();
				$this->displayHome();
				$this->smarty->assign('menuActive', 1);
				$this->smarty->assign('actionNews', 1);
				$template = 'index.tpl';
				break;
		}
		
		$this->smarty->display($template);
	} /*end function run()*/

	
	//left panel details (taken from db)
	private function prepareNews()
	{
		
		$this->smarty->assign('songs', $this->lang['common']['news']);
		
		$newsDb = new dataBase(false);
		$query = " SELECT * FROM `news` WHERE `possition` !=1 ORDER BY `datetime` DESC LIMIT 4";
		
		$newsDb->simpleQuery($query);
		$newsArr = $newsDb->dbResultFetchAll();
		
		foreach ($newsArr as $key => $newsRow) {
			$news[] =  array (
				'id' => $newsRow['id'],
				'name' => $newsRow['label'],
				'imag' => $newsRow['image'],
				'desc' => htmlspecialchars_decode($newsRow['text']),
				'link' => 'news/'.$newsRow['id'],
			);
		}
		$this->smarty->assign('songsItems', $news);
		$this->smarty->assign('newsLetterDisplay', 1);

	}
	
	private function buildMenu()
	{
		$menu = array(
					1 => array (
						'href' => '', 
						'value' => $this->lang['menu']['home']
						),
					2 => array (
						'href' => 'songs', 
						'value' => $this->lang['menu']['songs'],
						),
                    3 => array (
						'href' => 'news', 
						'value' => $this->lang['menu']['news'],
						),
                	4 => array (
						'href' => 'gallery', 
						'value' => $this->lang['menu']['gallery'],
						),
	                5 => array (
						'href' => 'about', 
						'value' => $this->lang['menu']['about'],
						),
    	            6 => array (
						'href' => 'contacts', 
						'value' => $this->lang['menu']['contacts'],
						),		
				);
		$this->smarty->assign('menu', $menu);
	}
	
	private function setCommonTemplateValues()
	{
		$this->smarty->assign('siteName',$this->siteDetails->name);
		$this->smarty->assign('siteSlogan', $this->siteDetails->slogan);
		$this->smarty->assign('pageTitle', $this->siteDetails->name);
		$this->smarty->assign('siteUrl', $this->siteDetails->siteUrl);
		$this->smarty->assign('keywords', $this->siteDetails->keywords);
		$this->smarty->assign('description', $this->siteDetails->description);
		$this->smarty->assign('lang', $this->lang);
	}
	
	private function displayHome()
	{
			
		$homeInfo = new dataBase(false);
		$query = "SELECT * FROM `news` WHERE `possition` = 1";
		
		$homeInfo->simpleQuery($query);
		$infos = $homeInfo->dbResultFetchAll();
		foreach ($infos as $key => $value) {
			$infos[$key]['text'] = htmlspecialchars_decode($value['text']);
			$infos[$key]['id'] = $value['id'];
		}
		
		$this->smarty->assign('mainItems', $this->prepareSmartyArray($infos));	
	}
	
	/**
	 * prepare data for displaying members of band
	 */
	private function displayAbout()
	{
		$aboutInfo = new dataBase(false);
		$query = "SELECT `id`, `label`, `image`, `text` FROM `members` WHERE 1";
		
		$aboutInfo->simpleQuery($query);
		$infos = $aboutInfo->dbResultFetchAll();
		
		$this->smarty->assign('mainItems', $this->prepareSmartyArray($infos));
	}
	
	
	/**
	 * prepare data to display songs (lyrics) 
	 */
	 private function displaySongs()
	 {
		$songsInfo = new dataBase(false);
		$query = "SELECT * FROM `songs` WHERE (`lyrics` IS NOT NULL)";
		$songsInfo->simpleQuery($query);
		$songs = $songsInfo->dbResultFetchAll(); 
		
		$authorsDb = new dataBase(false);
		$query = "SELECT id, nick, label FROM `members` WHERE 1";
		$authorsDb->simpleQuery($query);
		$authorsFromDB = $authorsDb->dbResultFetchAll();
		foreach ($authorsFromDB as $aut) {
			$authors[$aut['id']] = array (
					'nick' => $aut['nick'],
					'label' => $aut['label'],
				);
		} 
		
		// $this->debugy('authors', $authors, 1);
		
		foreach ($songs as $nr => $song) {
			$allSongs[] = array (
					'id' => $song['id'],
					'label' => $song['label'],
					'descr'=> $song['text'],
					'image' => $song['image'],
					'imageAlt' => $song['imageAlt'],
					'fileName' => $song['fileName'],
					'lyrics' => array (
									'lyrAuthor' => ($song['authorLyr']!= '') ? $song['authorLyr'] :  $authors[$song['authorLyrZespolId']]['label'], 
									'muzAuthor' => ($song['authorMusic']!= '') ? $song['authorMusic'] : $authors[$song['authorMusicZespolId']]['label'],
									'lyrTxt' => htmlspecialchars_decode($song['lyrics']),
				
					),
			);

			//left panel details
			$songList[] = array (
				'name'=> $song['label'],
				'desc'=> $song['text'],
				'link' => $this->siteDetails->siteUrl.'songs/'.$song['id']
			
			);
		}
		
		// chose song for display. 
		print $this->subAction; 
		if ($this->subAction != '') {
			$song4display = $this->subAction-1;
		} else {
			$song4display = rand(0, $songsInfo->rowCount()-1);
		}
		
		$songs4smarty[0] = $allSongs[$song4display];
		
		$this->smarty->assign('songs', $this->lang['songs']['songList']);
		//switch off newsletter div
		$this->smarty->assign('newsLetterDisplay', 0);
		
		
		$this->smarty->assign('songsItems', $songList);
		$this->smarty->assign('mainItems', $songs4smarty);
		
		$_POST['AllSongs'] = $allSongs;
		
	 }
	
	/**
	 * construct array ready to display in smarty
	 */
	private function prepareSmartyArray($infos)
	{
		foreach ($infos as $infoNr => $info) {
		// $this->debugy('z bazy danych', $info, 1);
			
		$mainItems[] = array (
					'id' => $info['id'],
					'label' => $info['label'],
					'image' => $info['image'],
					'imageAlt' => isset($info['imageAlt']) ? $info['imageAlt'] : $this->lang['common']['noPhotoTxt'],
					'descr' => $info['text'],
					'autor' => isset($info['zespol_id']) ? $info['zespol_id'] : '',
			);
		}
		return $mainItems;
	}
	
	/**
	 * add email of fan to database
	 */
	private function addEmail()
	{
		
	}
	
	private function displayContacts()
	{
		$mainItems = array (
					1 => array (
							'label' => $this->lang['menu']['contacts'],
							'image' => 'templatemo_image_01.jpg',
							'descr' => '<p>telefon: 798 835 592 </p>email:  Lza[małpka]tlen.pl</p> <p>poczta starodawna:<br/> Strachy na strychu<br/> Włóczynutka<br/>Iwanowice Dworskie 117E<br/>31-095 Iwanowice</p><script type="text/javascript" src="//cdn.dev.skype.com/uri/skype-uri.js"></script><script type="text/javascript" src="http://cdn.dev.skype.com/uri/skype-uri.js"></script>Skype Łza: <a href="skype:wloczynutka?chat"><img src="http://mystatus.skype.com/smallclassic/wloczynutka" /></a>',
						),
					);
		
		$this->smarty->assign('mainItems', $mainItems);	
	}



	
	/**
	 * display debug on screen  
	 *
	 * @param $dump 0 - string, 1-printR 2 -vardump
	 */
	private function debugy($title, $variable, $dump=0)
	{
		if ($this->debug == false) {
			return false;
		}
		if ($dump == 0) {
			print "# $title : $variable <br>";
		}
		if ($dump == 1) {
			print "<pre># $title -----";
			print_r($variable);
			print "_____</pre>";
		}
		if ($dump == 2) {
			print "# $title<br>";
			var_dump($variable);
			print '<br>';
		}
		
	}
	
}

$run = new MainRun();
$run->run();
?>